﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Membership.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class AccountController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult GoTo(int? id, string guid, string username, string email)
        {
            if(!id.HasValue)
            {
                dynamic m = null;
                if(!String.IsNullOrWhiteSpace(guid))
                {
                    m = Svc.ProcessOperation("GetAccountByGuid", new
                    {
                        Guid = guid.ParseAs<Guid>()
                    });
                }
                else if(!String.IsNullOrWhiteSpace(username))
                {
                    m = Svc.ProcessOperation("GetAccountByUsername", new
                    {
                        Username = username
                    });
                }
                else if(!String.IsNullOrWhiteSpace(email))
                {
                    m = Svc.ProcessOperation("GetAccountByEmail", new
                    {
                        Email = email
                    });
                }
                if(m == null)
                    return HttpNotFound();
                id = JDM.Int32(m.EntityID);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Create(int localizationProfileID,
            string email,
            string username,
            string password,
            string[] flags)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateAccount", new
                {
                    LocalizationProfileID = localizationProfileID,
                    Email = HtmlUtility.Encode(email),
                    Username = username,
                    Password = password,
                    Flags = flags.Merge(",")
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetAccount", new
            {
                EntityID = id,
                Fetch = "Entire"
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id,
            int localizationProfileID,
            string email,
            string username,
            string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateAccount", new
                {
                    EntityID = id,
                    LocalizationProfileID = localizationProfileID,
                    Email = email,
                    Username = username,
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpPost, PersistState]
        public ActionResult BulkAttributeUpdate(int accountID, IDictionary<String, String> attributes)
        {
            try
            {
                Svc.ProcessOperation("BulkUpdateAccountAttributes", new
                {
                    HolderID = accountID,
                    Attributes = attributes
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = accountID
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteAccount", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Activate(int id)
        {
            try
            {
                Svc.ProcessOperation("ActivateAccount", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Deactivate(int id)
        {
            try
            {
                Svc.ProcessOperation("DeactivateAccount", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult InitVerification(int id)
        {
            try
            {
                Svc.ProcessOperation("InitAccountVerification", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult CommitVerification(int id, Guid code)
        {
            try
            {
                Svc.ProcessOperation("CommitAccountVerification", new
                {
                    EntityID = id,
                    VerificationCode = code
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult CloseSession(int accountID, int sessionID)
        {
            try
            {
                Svc.ProcessOperation("CloseSession", new
                {
                    EntityID = sessionID
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = accountID
            }));
        }

        [HttpPost, PersistState]
        public ActionResult SetPassword(int id, string password)
        {
            try
            {
                Svc.ProcessOperation("ChangeAccountPassword", new
                {
                    EntityID = id,
                    Password = password
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        #endregion

        #region Child Actions

        [ChildActionOnly]
        public ActionResult _Comments(int accountID)
        {
            dynamic m = new ExpandoObject();

            m.EntityID = accountID;
            m.Comments = Svc.ProcessOperation("SearchAccountComments", new
            {
                HolderID = accountID
            }, new
            {
                DisclosureLevel = "Extended"
            }).Items;
            return PartialView(m);
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page,
            int? rows,
            string sord,
            string sidx,
            string searchTerm,
            int? roleID,
            int? localizationProfileID,
            string createdFrom,
            string createdTo,
            string flagMask)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchAccounts", new
            {
                Term = new
                {
                    Expression = searchTerm
                },
                RoleID = roleID,
                LocalizationProfileID = localizationProfileID,
                FlagMask = flagMask,
                CreatedFrom = String.IsNullOrWhiteSpace(createdFrom) 
                    ? (DateTime?)null 
                    : Svc.DateTime(createdFrom),
                CreatedTo = String.IsNullOrWhiteSpace(createdTo) 
                    ? (DateTime?)null 
                    : Svc.DateTime(createdTo),
                Index = page * rows,
                Count = rows,
                SortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Base"
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.String(i.Username),
                    JDM.String(i.Email),
                    Svc.DateTime((DateTime)JDM.DateTime(i.CreatedOn))
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        [HttpPost]
        public ActionResult Autocomplete(string term)
        {
            var m = Svc.ProcessOperation("GetAccountDictionary", new
            {
                Term = new
                {
                    Expression = String.Format("{0}%", term)
                },
                Count = 10
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new
                {
                    id = JDM.String(i.Key),
                    value = JDM.String(i.Value)
                });
            }
            return Json(data.ToArray());
        }

        #endregion
    }
}
